package com.bum.rss.bo;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bum.rss.exp.om.Rss;
import com.bum.rss.exp.om.RssEntry;
import com.bum.rss.site.Site;

public class SiteBO {
	static Log	log	= LogFactory.getLog(SiteBO.class);

	SiteFactory	siteFactory;
	SiteLoader	siteLoader;

	public List<RssEntry> getSitemap() {
		List<RssEntry> list = new LinkedList<RssEntry>();

		List<RssEntry> siteEntrys = siteFactory.getSiteEntrys();
		list.addAll(siteEntrys);

		for (RssEntry siteEntry : siteEntrys) {
			Site site = siteFactory.get(siteEntry.getUrl());
			List<RssEntry> cats = site.listSiteCats(null);
			if (CollectionUtils.isNotEmpty(cats)) {
				list.addAll(cats);
			}
		}

		return list;
	}

	public Rss load(String url, String user) {
		if (StringUtils.isBlank(url)) {
			return listSites(user);
		}

		String[] parts = StringUtils.split(url, "/", 3);
		;
		if (parts.length == 0) {
			return listSites(user);
		}

		String siteCode = parts[0].toLowerCase();

		Site site = siteFactory.get(siteCode);
		if (site == null) {
			if (log.isDebugEnabled()) {
				log.debug("NO HANDLER: url: " + url + ", site: " + siteCode + " nick: " + user);
			}
			return null;
		}

		switch (parts.length) {
			case 1:
				if (site.getHomeCat() != null) {
					return listCatEntrys(site.getCode() + "/" + site.getHomeCat(), site, site.getHomeCat(), user);
				}
				
				return listSiteCats(url, site, user);

			case 2:
				if (Site.MENU_CAT.equals(parts[1])) {
					return listSiteCats(url, site, user);
				}

				return listCatEntrys(url, site, parts[1], user);

			case 3:
				return loadEntry(url, site, parts[2], user);
		}

		return null;
	}

	public Rss listSites(String user) {
		Rss rss = new Rss(Rss.TYPE_SITES);
		rss.setEntries(siteFactory.getSiteEntrys());
		return rss;
	}

	public Rss listSiteCats(String url, Site site, String user) {
		List<RssEntry> cats = siteLoader.listSiteCat(site, user);
		Rss rss = new Rss(Rss.TYPE_CATS);
		rss.setEntries(cats);
		return rss;
	}

	public Rss listCatEntrys(String url, Site site, String cat, String user) {
		List<RssEntry> entrys = siteLoader.listCatEntrys(url, site, cat, user);
		Rss rss = new Rss(Rss.TYPE_ENTRYS);
		rss.setEntries(entrys);
		return rss;
	}

	public Rss loadEntry(String url, Site site, String path, String user) {
		RssEntry entry = siteLoader.loadEntry(url, site, path, user);

		Rss rss = new Rss(Rss.TYPE_CONTENT);
		rss.setEntry(entry);
		return rss;
	}

	/**
	 * SETTERS
	 */
	public void setSiteFactory(SiteFactory siteFactory) {
		this.siteFactory = siteFactory;
	}

	public void setSiteLoader(SiteLoader siteLoader) {
		this.siteLoader = siteLoader;
	}
}
